import time
import logging
import pandas as pd
import requests


from QFinanceGridModel.base import Url, Headers


logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class Collector:
    """
    收集器，根据市场资金流向，获取行业/概念中的资金流向的个股信息，以及个股的日K数据
    """

    def __init__(self, type, secid=None):
        self.__type = type
        self.__secid = secid

        url = Url(self.__type,  self.__secid)
        headers = Headers(self.__type, self.__secid)

        self.__url = str(url.base_url)
        self.__params = url.params
        self.__headers = headers.headers

    def run(self) -> pd.DataFrame:
        try:
            response = requests.get(
                url=self.__url,
                params=self.__params,
                headers=self.__headers,
                timeout=30
            )
            response.raise_for_status()
            data = response.json()
            # 检查数据有效性
            if 'data' not in data or 'diff' not in data['data']:
                logger.warning(f"未获取到有效数据")
                return pd.DataFrame()

            # 处理数据
            records = []
            for idx, item in enumerate(data['data']['diff'], start=1):
                record = {
                    "代码": str(item.get("f13", ""))+"."+item.get("f12", ""),  # f13 =1 沪，=0 深，90表示板块/行业/概念
                    "名称": item.get("f14", ""),
                    "最新价": item.get("f2", 0),
                    "今日涨幅(%)": item.get("f3", 0),
                    "个股代码": item.get("f205", ""),
                    "个股名称": item.get("f204", ""),
                    "净流入(亿)": item.get("f62", 0),
                    "净占比(%)": item.get("f184", 0),
                    # "超大单净流入(元)": item.get("f66", 0),
                    # "超大单净占比(%)": item.get("f69", 0),
                    # "大单净流入(元)": item.get("f72", 0),
                    # "大单净占比(%)": item.get("f75", 0),
                    "时间": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item.get("f124", 0)))
                }
                records.append(record)
            df = pd.DataFrame(records)
            # 转换成亿
            df["净流入(亿)"] = pd.to_numeric(df["净流入(亿)"], downcast='float', errors="coerce").apply(lambda x: x/100000000.0)

        except requests.exceptions.RequestException as e:
            logger.error(f"请求失败: {str(e)}")
        except (ValueError, KeyError) as e:
            logger.error(f"数据处理错误: {str(e)}")
        except Exception as e:
            logger.error(f"未知错误: {str(e)}")
        return df


if __name__ == "__main__":
    # c = Collector(type="4", secid="BK0464")
    c = Collector(type="3")  # BK0545 #BK0464
    df = c.run()
    if not df.empty:
        pd.set_option('display.width', 1000)
        pd.set_option('display.max_columns', None)
        pd.set_option('display.max_colwidth', 50)
        pd.set_option('display.float_format', lambda x: f"{x:,.2f}")
        print("\n获取结果:")
        print(df.head(20))
        print(f"\n总共获取 {len(df)} 条记录")

    else:
        print("未获取到有效数据")
